package com.situ.staff.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.staff.bean.Dept;
import com.situ.staff.service.DeptService;

@Controller
@RequestMapping("/dept")
public class DeptController {

	@Autowired
	DeptService deptService;

	@RequestMapping("/add")
	public String add(Dept dept, Model model) {

		try {
			int add = deptService.add(dept);
			if (add > 0) {
				List<Dept> depts = deptService.getAll();
				model.addAttribute("depts", depts);
				return "dept/list";
			} else {
				model.addAttribute("error", "未知错误");
				return "dept/add";
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "dept/add";
		}

	}

	@RequestMapping("/list")
	public String list(Model model) {
		List<Dept> depts = deptService.getAll();
		model.addAttribute("depts", depts);
		return "dept/list";
	}

	@RequestMapping("/remove")
	public String remove(int id, Model model) {
		deptService.remove(id);
		List<Dept> depts = deptService.getAll();
		model.addAttribute("depts", depts);
		return "dept/list";

	}

	@PostMapping("/getAll")
	@ResponseBody
	public List getAll() {
		List depts = deptService.getAll();
		return depts;
	}

	@RequestMapping("/editById")
	public String getById(int id, Model model) {
		System.out.println(id);
		Dept dept = deptService.getById(id);
		model.addAttribute("dept", dept);
		return "dept/edit";
	}

	@RequestMapping("/edit")
	public String edit(Dept dept, Model model) {

		try {
			deptService.update(dept);
			List depts = deptService.getAll();
			model.addAttribute("depts", depts);
			return "dept/list";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "dept/edit";
		}

	}
}
